package com.meisupic.copyright.support;

import com.alibaba.fastjson.JSON;
import com.meisupic.copyright.exception.BizException;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.orm.ObjectOptimisticLockingFailureException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * creation wuxun
 * @version V1.0
 * @Description: TODO
 * @date 2018/1/14 19:35
 */
@ControllerAdvice
public class MvcExceptionHandler {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Message error(Exception e) {
        logger.error(e.getMessage(), e);
        return Message.error("系统错误！");
    }

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public Message error(BizException e) {
        logger.error(e.getMessage());
        return Message.error(e.getMessage());
    }


    /**
     * 参数验证失败异常
     */
    @SuppressWarnings("rawtypes")
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Message paramInvalid(MethodArgumentNotValidException e) {
        BindingResult bindingResult = e.getBindingResult();
        logger.warn("错误参数：{}", JSON.toJSONString(bindingResult.getTarget()));
        List<ObjectError> errors = bindingResult.getAllErrors();
        ObjectError oe = errors.get(0);
        return Message.error(oe.getDefaultMessage());
    }


    /**
     * 数据库乐观锁异常
     * @param e
     * @return
     */
    @ExceptionHandler(ObjectOptimisticLockingFailureException.class)
    @ResponseBody
    public Message paramInvalid(ObjectOptimisticLockingFailureException e) {
        logger.error(e.getMessage(), e);
        return Message.error("数据已过期，请刷新后重试");
    }
}
